package admin

import (
	"ginblog/api/common"
	"ginblog/model"
	"ginblog/tools/jwt"
	"github.com/gin-gonic/gin"
)

type LoginV1 struct {
	common.LoginBase
	AdminName string
}

func (Login *LoginV1) IsSetUserName() bool {
	return Login.AdminName != ""
}

// DoLogin /** 登陆主入口
func (Login *LoginV1) DoLogin(c *gin.Context) {
	//用户密码不能为空
	if !Login.IsSetPassword() {
		Login.LoginFail(c)
		return
	}
	admin := model.Admin{}
	//是否是手机号登陆
	if Login.IsSetPhone() {
		admin.Phone = Login.Phone
		Login.QueryLogin(c, &admin)
		return
	}
	//是否是邮箱登陆
	if Login.IsSetEmail() {
		admin.Email = Login.Email
		Login.QueryLogin(c, &admin)
		return
	}
	//是否是用户名登陆
	if Login.IsSetUserName() {
		admin.AdminName = Login.AdminName
		Login.QueryLogin(c, &admin)
		return
	}
	Login.LoginFail(c)
}

// QueryLogin /** 查询登陆
func (Login *LoginV1) QueryLogin(c *gin.Context, a *model.Admin) {
	err := model.Db.Where(a).First(a).Error
	if err != nil {
		Login.LoginFail(c)
		return
	}
	if !a.ExaminePassWord(a.PassWordEncrypt(Login.Password)) {
		Login.LoginFail(c)
		return
	}
	flag, token := jwt.SetToken(c, a)
	if !flag {
		Login.LoginFail(c)
		return
	}
	data := map[string]string{
		"token":     token,
		"adminname": a.AdminName,
	}
	Login.LoginSuccess(c, data)
	return
}
